import Java from "frida-java-bridge";
import { log } from "./logger.js";

function hook_android_handler_removeCallbacksAndMessages() {
    Java.perform(() => {
        // 获取android.os.Handler类
        const Handler = Java.use('android.os.Handler');
        // Hook removeCallbacksAndMessages方法
        Handler.removeCallbacksAndMessages.implementation = function (token: any) {
            const Looper = Java.use('android.os.Looper');
            const mainLooper = Looper.getMainLooper();
            const currentLooper = this.getLooper();

            if (currentLooper.equals(mainLooper) && token === null) {
                // 打印方法调用信息
                send('[+] Handler.removeCallbacksAndMessages called on main looper with null token');

                // 打印调用栈
                send('    Call stack:');
                const Thread = Java.use('java.lang.Thread');
                const stack = Thread.currentThread().getStackTrace();

                for (let i = 3; i < stack.length; i++) {
                    const element = stack[i];
                    send(`        at ${element.getClassName()}.${element.getMethodName()}(${element.getFileName()}:${element.getLineNumber()})`);
                }
            }

            // 调用原始方法
            return this.removeCallbacksAndMessages(token);
        };
    });

}

function hook_android_sim_region() {
    Java.perform(function () {
        const TelephonyManager = Java.use('android.telephony.TelephonyManager');

        // Hook SIM卡国家码获取方法
        TelephonyManager.getSimCountryIso.overload().implementation = function () {
            const original = this.getSimCountryIso();
            send(`[SIM] getSimCountryIso => ${original}`);
            return original; // 返回原始值避免检测
        };

        // Hook 网络国家码获取方法
        TelephonyManager.getNetworkCountryIso.overload().implementation = function () {
            const original = this.getNetworkCountryIso();
            send(`[NETWORK] getNetworkCountryIso => ${original}`);
            return original;
        };

        // Hook 双重SIM卡支持（API Level 24+）
        TelephonyManager.getSimCountryIso.overload('int').implementation = function (slotIndex: number) {
            const original = this.getSimCountryIso(slotIndex);
            send(`[SIM${slotIndex}] getSimCountryIso => ${original}`);
            return original;
        };

        send('[+] SIM卡区域监控已激活');
    });
}

if (Java.available) {
    log("Java VM available");
    Java.perform(function () {
        send({type: "status",message: "Application class-loader now available"});
    })
    // hook_android_handler_removeCallbacksAndMessages();
    hook_android_sim_region();
    log("load all hook end");
} else {
    log("No Java VM in this process");
}